package com.onlinesys.database;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class DBManager {

    private static DataSource ds = null;

    public static void initDBConnection() {
        InitialContext ctx;
        try {
            ctx = new InitialContext();
            ds = (DataSource) ctx.lookup("java:comp/env/jdbc/MySQL");
        } catch (NamingException e) {
            e.printStackTrace();
        }
    }

    public synchronized static Connection getDBConnection() throws SQLException {
        if (ds == null) {
            initDBConnection();
        }

        return ds.getConnection();
    }

    public static void free(ResultSet rs, Statement stmt, Connection conn) throws SQLException {
    	if (rs != null && !rs.isClosed()) {
            rs.close();
        }
    	
        if (stmt != null && !stmt.isClosed()) {
            stmt.close();
        }
        if (conn != null && !conn.isClosed()) {
            conn.close();
        }
    }

}
